function killerrors(){ return true; }
//window.onerror = killerrors;

function trim(strl){
    strl = strl+"";
    return strl.replace(/(^\s*)|(\s*$)|(\n$)|(^\n)/g, "");
}

//删除字符串左边的空格回车
function ltrim (str){
    return str.replace(/(^\s*)|(^\n)/g, "");
}

function rtrim(str){
    return this.replace(/(\s*$)|(\n$)/g, "");
}

function hasClass(ele,cls) {
	return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)')); 
} 

function addClass(ele,cls) { 
	if (!this.hasClass(ele,cls)) ele.className += " "+cls; 
} 

function removeClass(ele,cls) { 
	if (hasClass(ele,cls)) { 
		var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)'); 
		ele.className=ele.className.replace(reg,' '); 
	} 
} 
function loadJs(src){
	var obj = document.createElement('script');
	obj.src = src;
	var s = document.getElementsByTagName('script')[0];
	s.parentNode.insertBefore(obj, s);
}
function SetCookie(name,value)//两个参数，一个是cookie的名子，一个是值
{
	var Days = 30; //此 cookie 将被保存 30 天
	var exp = new Date();    //new Date("December 31, 9998");
	exp.setTime(exp.getTime() + Days*24*60*60*1000);
	document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}

function getWinHeigh(){
    win_height = document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
    return win_height
}

function getWinWidth(){
    win_width = document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth;
    return win_width;
}

function selectCheckBox(name){
    var l = new Array();
    var el = document.getElementsByTagName('input');
    var len = el.length;
    for(var i=0; i<len; i++) {
        if( (el[i].type=="checkbox") && (el[i].name==name) && (el[i].checked==true)) {
            l.push(el[i].value)
        }
    }
    return l;
}

/**
 * 全选
 * @param name
 */
function checkAll(name) {
    var el = document.getElementsByTagName('input');
    var len = el.length;
    for(var i=0; i<len; i++) {
        if((el[i].type=="checkbox") && (el[i].name==name)) {
            el[i].checked = true;
        }
    }
}

/**
 * 反选
 * @param name
 */
function fCheckAll(name){
    var el = document.getElementsByTagName('input');
    var len = el.length;
    for(var i=0; i<len; i++) {
        if((el[i].type=="checkbox") && (el[i].name==name)) {
            if(el[i].checked){
                el[i].checked = false;
            }else{
                el[i].checked = true;
            }
        }
    }
}
/*
*
* 取消全选
 */
function clearAll(name) {
    var el = document.getElementsByTagName('input');
    var len = el.length;
    for(var i=0; i<len; i++) {
        if((el[i].type=="checkbox") && (el[i].name==name)) {
            el[i].checked = false;
        }
    }
}

function lightbox(){
    _id = "lightbox"
    if(document.getElementById(_id) == null){
        var l = document.createElement("div");
        l.id = _id;
        l.className = "lightbox"
        l.style.width = getWinWidth()+"px";
        l.style.height = getWinHeigh()+"px";
        document.body.appendChild(l);
    }else{
        var l = document.getElementById(_id)
        l.className = "lightbox"
        l.style.width = getWinWidth()+"px";
        l.style.height = getWinHeigh()+"px";
    }
}
function unlightbox(){
    _id = "lightbox"
    var l = document.getElementById(_id)
    if(l!=null){
        l.className = "";
        l.style.width = "0px";
        l.style.height = "0px"
    }
}

function dialog(obj,data,callback){
    lightbox()
    obj.innerHTML = "";
    dialogShow(obj)
    var docWidth = getWinWidth();
    var docHeight = getWinHeigh();
    if(!hasClass(obj,"dialog")){
        addClass(obj,"dialog");
    }

    var dWidth = data["width"];
    var dHeight = data["height"];
    var bodyTop = parseInt((docHeight-dHeight) /2)
    var bodyLeft = parseInt((docWidth-dWidth) / 2)
    var tb = data["titleHeight"]==undefined ? false : true;
    var bb = data["buttom"]==undefined ? false : true;
    var buttomH = 43;
    var titleH = tb ?  data["titleHeight"] : 35;
    var bodyH = bb ? dHeight - buttomH - titleH : dHeight - titleH;

    obj.style.left = bodyLeft+"px";
    obj.style.top = bodyTop+"px";

    var titleDiv = document.createElement("div");
    var dTitleDiv = document.createElement("div");
    var closeDiv = document.createElement("div");
    var closeImg = document.createElement("img");

    var bodyDiv = document.createElement("div");
    var buttomDiv = document.createElement("div");

    titleDiv.className = "title"
    titleDiv.style.height = titleH + "px";
    titleDiv.style.lineHeight = titleH + "px";
    titleDiv.style.width = dWidth + "px";

    dTitleDiv.className = "dtitle"
    dTitleDiv.style.height = titleH + "px";
    dTitleDiv.style.lineHeight = titleH + "px";
    dTitleDiv.style.width = dWidth-35 + "px";
    dTitleDiv.innerHTML = data['title']

    closeDiv.className = "close"
    closeDiv.style.height = titleH + "px";
    closeDiv.style.lineHeight = titleH + "px";
    closeDiv.style.width = "30px"
    closeImg.src = "/tpl/static/close.png"
    closeImg.style.height = titleH + "px";
    closeImg.onclick = function(){
        dialogHide(this.parentNode.parentNode.parentNode)
    }
    closeDiv.appendChild(closeImg)

    titleDiv.appendChild(dTitleDiv)
    titleDiv.appendChild(closeDiv)

    bodyDiv.className = "body"
    bodyDiv.style.height = bodyH + "px";
    bodyDiv.style.width = dWidth + "px";
    if(data['content']['type']=="iframe"){
        iframeEle = document.createElement("iframe");
        iframeEle.style.width = dWidth + "px";
        iframeEle.style.height = bodyH + "px";
        iframeEle.frameborder = 0
        iframeEle.style.border = "none";
        iframeEle.src = data['content']['body'];
        if(data['content']['id']!=undefined){
            iframeEle.id = data['content']['id']
        }
        if(typeof callback == "function"){
            iframeEle.onload = callback
        }
        bodyDiv.appendChild(iframeEle)
    }
    if(bb){//如果存在按钮
        buttomDiv.className = "buttom"
        buttomDiv.style.width = dWidth + "px"

        for(var i in data["buttom"]){

            var btn = data["buttom"][i];
            if(btn["caption"]==undefined){
                continue
            }
            var btnSpan = document.createElement("span")
            btnSpan.className = "b"
            btnSpan.innerHTML = btn["caption"]
            if(typeof btn['callback'] == "function"){
                btnSpan.onclick = btn['callback']
            }
            buttomDiv.appendChild(btnSpan)
        }
    }
    obj.appendChild(titleDiv)
    obj.appendChild(bodyDiv)
    if(bb){
        obj.appendChild(buttomDiv)
    }

    //data={width:200,heihgt:300,titleHeight:35,title:"标题","content":{type:"iframe","http://www.qq.com"},"buttom":[{caption:"Yes",callback}]}
}

function dialogShow(obj){
    obj.style.display = "block";
}
function dialogHide(obj){
    obj.style.display = "none";
    unlightbox()
}

/**
 *
 * @param id iframe 的 id
 * @param iid iframe 里面内容的 id
 */
function iframeObj(id,iid){

    return document.getElementById(id).contentWindow.document.getElementById(iid)
}

function iframeClassObj(id,cname){
    return document.getElementById(id).contentWindow.document.getElementsByClassName(cname)
}

function stringify(o){
    var r = [];
    if(typeof o =="string") return "\""+o.replace(/([\'\"\\])/g,"\\$1").replace(/(\n)/g,"\\n").replace(/(\r)/g,"\\r").replace(/(\t)/g,"\\t")+"\"";
    if(typeof o == "object"){
        if(!o.sort){
            for(var i in o)
                r.push(i+":"+stringify(o[i]));
            if(!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)){
                r.push("toString:"+o.toString.toString());
            }
            r="{"+r.join()+"}"
        }else{
            for(var i =0;i<o.length;i++)
                r.push(stringify(o[i]))
            r="["+r.join()+"]"
        }
        return r;
    }
    return o.toString();
}

/*!
 * 一个简单的Ajax类
 *
 * @param function fnBefore     用户自定义函数 Ajax开始前执行，若无则为null
 * @param function fnAfter      用户自定义函数 Ajax完成后执行，若无则为null
 * @param function fnTimeout    用户自定义函数 Ajax请求超时后执行，若无则为null
 * @param integer  iTime        设置超时时间 单位毫秒
 * @param boolean  bSync        是否为同步请求，默认为false
 */

function Ajax(fnBefore,fnAfter,fnTimeout,iTime,bSync){
    this.before		= fnBefore;
    this.after		= fnAfter;
    this.timeout	= fnTimeout;
    this.time		= iTime ? iTime : 10000;
    this.async		= bSync ? false : true;
    this._request	= null;
    this._response	= null;
}

Ajax.prototype = {
    /**
     *  将需要发送的数据进行编码
     *
     *  @param object data  JSON格式的数据，如: {username:"fyland",password:"ichenshy"}
     */
    formatParam : function( data ){
        if ( ! data || typeof data != "object" ) return data;
        var k,r = [];
        for ( k in data ) {
            r.push([k,'=',encodeURIComponent(data[k])].join(''));
        }
        return r.join('&');
    },

    /**
     * 创建 XMLHttpRequest对象
     */
    create : function(){
        if( window.XMLHttpRequest ) {
            this._request = new XMLHttpRequest();
        } else {
            try {
                this._request = new window.ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {}
        }
    },

    /**
     * 发送请求
     *
     * @param string				url     请求地址
     * @param object or string   data    可以是字符串或JSON格式的数据，如: {username:"fyland",password:"ichenshy"}
     * @param string             method  请求方式 ： GET or POST
     * @param boolean            ifCache	返回数据是否在浏览器端缓存，默认为false;
     */
    send : function(url,data,method,ifCache){
        if ( typeof this.before == "function" ) this.before();

        method = method.toUpperCase();
        this.create();

        var self = this;
        var timer = setTimeout(function(){
            if ( typeof self.timeout == "function" ) self.timeout();
            if ( self._request ) {
                self._request.abort();
                self._request = null;
            }
            return true;
        },this.time);

        var sendBody  = this.formatParam(data);

        if ( 'GET' == method ) {
            url = [url, ( url.indexOf('?') == -1 ? '?' : '&') ,sendBody].join('');
            sendBody = null;
        }

        if ( ! ifCache ) {
            url = [url, ( url.indexOf('?') == -1 ? '?' : '&') , "ajaxtimestamp=" , (new Date()).getTime()].join('');
        }

        this._request.open(method,url,this.async);
        if ( "POST" == method ) this._request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        this._request.onreadystatechange = function(){
            if( self._request.readyState==4 ){
                if ( self._request.status==200 ){
                    if ( timer ) clearTimeout(timer);
                    self._response = self._request.responseText;
                    if ( typeof self.after == "function") self.after(self._response);
                }
            }
        }
        this._request.send( sendBody );
    },

    /**
     *   简单的GET请求
     *
     *   @param string url  请求地址
     *   @param null or string or object	data
     *   @param object html element or string id	  e
     *   @param string loading                     loading时在e中的显示
     *   @param boolean  ifCache    浏览器是否缓存
     */
    get : function(url,data,e,loading,ifCache){
        if ( typeof e == "string" ) e = document.getElementById(e);
        if ( loading ) {
            var rg = /\.(gif|jpg|jpeg|png|bmp)$/i;
            if ( rg.test(loading) ){
                loading = ['<img src="', loading , '"  align="absmiddle" />'].join('');
            }
            this.before = function(){e.innerHTML = loading;}
        }
        this.after		= function(s){e.innerHTML = s;}
        this.timeout	= function(){e.innerHTML = ' 请求超时! ';}
        this.send(url,data,"GET",ifCache ? true : false);
    }
};

function buildGet(jsondata){
    var g = "";
    var j = "";
    for(var i in jsondata){
        g += j+i+"="+jsondata[i];
        j="&";
    }
    return g;
}

function formatDate(v){

    if(v instanceof Date){

        var y = v.getFullYear();

        var m = v.getMonth() + 1;

        var d = v.getDate();

        var h = v.getHours();

        var i = v.getMinutes();

        var s = v.getSeconds();

        var ms = v.getMilliseconds();

        if(ms>0) return y + '-' + m + '-' + d + ' ' + h + ':' + i + ':' + s + '.' + ms;

        if(h>0 || i>0 || s>0) return y + '-' + m + '-' + d + ' ' + h + ':' + i + ':' + s;

        return y + '-' + m + '-' + d;

    }

    return '';

}